package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.api.dto.*;
import com.jmp.base.dto.SeeRecordWebsiteRequest;
import com.jmp.base.dto.WebsiteVideoDto;
import com.jmp.base.dto.WebsiteVideoVo;
import com.jmp.feign.SeeRecordFeign;
import com.jmp.feign.WebsiteFeign;
import com.jmp.util.LabelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageResponse2;
import one.stand.enums.SeeRecordEnums;
import one.stand.mapper.CompanyRecruitMapper;
import one.stand.mapper.GoodsApiCrmJxsMapper;
import one.stand.model.*;
import one.stand.service.*;
import one.stand.util.*;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Api(description = "店铺页")
@RequestMapping("/supplier")
@RestController
public class SupplierController {

    @Autowired
    private SeeRecordFeign seeRecordFeign;
    @Autowired
    private WebsiteFeign websiteFeign;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private WebsiteService websiteService;
    @Autowired
    private RecordPublicService recordPublicService;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private CompanyShowroomService companyShowroomService;
    @Autowired
    private CompanyRecruitMapper companyRecruitMapper;
    @Autowired
    private GoodsBaseService goodsBaseService;

    @Autowired
    private GoodsApiCrmJxsMapper goodsApiCrmJxsMapper;

    @ApiOperation(value = "店铺信息")
    @PostMapping("/info")
    public ResultModel<SupplierInfoResponse> companyInfo(@RequestAttribute SupplierInfoRequest request) {
        AssertUtil.isTrue(Objects.nonNull(request) && Objects.nonNull(request.getCompanyId()), ResultEnum.PARAM_CHECK);

        RequestContext.User user = RequestContextHolder.getRequestContext().getUser();
        final boolean isLogin = Objects.nonNull(user);
        final Integer optUserId = isLogin ? user.getUserId() : null;

        String key = "api:jxs:supplierInfo;" + request.getCompanyId() + ":" + optUserId;
        SupplierInfoResponse responseResultModel = redisUtil.get(key);
        if (Objects.nonNull(responseResultModel)) {
            return ResultModel.success(responseResultModel);
        }

        Company companyModel = companyBaseService.getById(request.getCompanyId());
        AssertUtil.nonNull(companyModel, ResultEnum.NO_DATA);

        Website website = websiteService.getByCompanyId(request.getCompanyId());
        String companyPhoto = StringUtils.EMPTY;
        if (Objects.nonNull(website) && StringUtils.isNoneBlank(website.getPhotos())) {
            companyPhoto = website.getPhotos().split(",")[0];
        }

        //是否收藏: 1收藏 2未收藏
        int isCollection = 2;
        if (isLogin) {
            isCollection = recordPublicService.isCollection(optUserId, RecordPublicService.ITEMTYPE_COMPANY, request.getCompanyId()) ? 1 : 2;
        }

        //商品分类
        List<GoodsType> goodstypeModelList = goodsApiCrmJxsMapper.selectTypes(companyModel.getCompanyId());
        List<SupplierInfoResponse.Type> types = OneListUtil.group(goodstypeModelList,
                goodsType -> goodsType.getParentId() == 0,
                GoodsType::getGoodstypeId,
                GoodsType::getParentId,
                (parent, child) -> parent.getChildList().add(child),
                goodsType -> SupplierInfoResponse.Type.builder()
                        .goodstypeId(goodsType.getGoodstypeId())
                        .name(goodsType.getName())
                        .childList(Lists.newLinkedList())
                        .build(),
                goodsType -> SupplierInfoResponse.Type.builder()
                        .goodstypeId(goodsType.getGoodstypeId())
                        .name(goodsType.getName())
                        .build());

        CompanyShowroom companyShowroom = companyShowroomService.getByCompanyId(request.getCompanyId());

        SupplierInfoResponse response = SupplierInfoResponse.builder()
                .userLogo(null)
                .companyLogo(companyModel.getCompanyLogo())
                .companyName(companyModel.getCompanyName())
                .isCollection(isCollection)
                .goodstypeModelList(types)
                .companyPhoto(companyPhoto)
                .vrUrl(Objects.nonNull(companyShowroom) ? companyShowroom.getVrUrl() : null)
                .build();

        redisUtil.set(key, response, 5, TimeUnit.MINUTES);
        return ResultModel.success(response);
    }

    @ApiOperation(value = "产品列表")
    @PostMapping("/goods")
    public ResultModel<SupplierGoodsResponse> goods(@RequestAttribute SupplierGoodsRequest request) {
        AssertUtil.nonNull(request.getCompanyId(), ResultEnum.PARAM_CHECK);

        String key = "api:jxs:supplierGoodsList;" + request.getCompanyId() + ":" + request.getGoodstypeId() + ":" + request.getGoodsName() + ":" + request.getPageNum() + ":" + request.getPageSize();
        SupplierGoodsResponse resultModel = redisUtil.get(key);
        if (Objects.nonNull(resultModel)) return ResultModel.success(resultModel);

        String goodsNameLike = SqlUtil.like(request.getGoodsName());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Goods> list = goodsApiCrmJxsMapper.selectSupplierGoods(request.getGoodstypeId(), request.getCompanyId(), goodsNameLike);
        PageResponse2<SupplierGoodsResponse.Goods> goodsPage = ConvertUtils.page2(list, goodsModel -> {
            boolean hasVr = StringUtils.isNoneBlank(goodsModel.getQjVrUrl());
            boolean hasAr = goodsBaseService.hasAr(goodsModel.getGoodsId());
            boolean hasVideo = StringUtils.isNoneBlank(goodsModel.getVideoUrl());
            boolean hasZkgx = companyBaseService.hasZkgx(goodsModel.getCompanyId());
            Company company = companyBaseService.getById(goodsModel.getCompanyId());
            String photo = goodsPhotoService.getPath(goodsModel.getGoodsId());
            Long popularityNum = recordPublicService.getPopularity(SeeRecordEnums.PRODUCT.getCode(), goodsModel.getGoodsId());

            return SupplierGoodsResponse.Goods.builder()
                    .goodsId(goodsModel.getGoodsId())
                    .goodsName(goodsModel.getGoodsName())
                    .goodPhoto(photo)
                    .photo(photo)
                    .price("价格详询客服")
                    .coverType(StringUtils.isNoneBlank(goodsModel.getQjVrUrl()) ? 1 : (StringUtils.isNoneBlank(goodsModel.getVideoUrl()) ? 2 : 0))
                    .labels(LabelUtil.getLabels(hasVr, hasAr, hasVideo, hasZkgx))
                    .hasZkgx(BooleanUtils.toInteger(hasZkgx))
                    .companyName(Objects.nonNull(company) ? company.getCompanyName() : null)
                    .popularityNum(popularityNum)
                    .build();
        });
        SupplierGoodsResponse response = SupplierGoodsResponse.builder()
                .goodsPage(goodsPage)
                .build();

        if (request.getPageNum() == 1) {//缓存第一页
            redisUtil.set(key, response, 5, TimeUnit.MINUTES);
        }
        return ResultModel.success(response);
    }

    @ApiOperation(value = "官网")
    @PostMapping("/website")
    public ResultModel<SupplierWebsiteResponse> getWebsiteInfo(@RequestAttribute SupplierWebsiteRequest request) {
        AssertUtil.nonNull(request.getCompanyId(), ResultEnum.PARAM_CHECK);

        Website model = websiteService.getByCompanyId(request.getCompanyId());
        Company company = companyBaseService.getById(request.getCompanyId());
        List<CompanyRecruitModel> recruitModels = companyRecruitMapper.select(new CompanyRecruitModel() {{
            setCompanyId(request.getCompanyId());
        }});
        //视频
        ResultModel<WebsiteVideoVo> resultModel = websiteFeign.video(WebsiteVideoDto.builder().companyId(request.getCompanyId()).build());
        AssertUtil.isTrue(resultModel);
        List<SupplierWebsiteResponse.Video> videoModels = ConvertUtils.list(resultModel.getData().getVideoList(), video -> {
            return SupplierWebsiteResponse.Video.builder()
                    .videoId(video.getVideoId())
                    .url(video.getUrl())
                    .describes(video.getDescribes())
                    .cover(video.getCover())
                    .sort(video.getSort())
                    .build();
        });

        //主推商品
        List<Goods> mainPush = goodsApiCrmJxsMapper.selectMainPush(request.getCompanyId());
        List<SupplierWebsiteResponse.Goods> mainGoodsList = ConvertUtils.list(mainPush, goods -> SupplierWebsiteResponse.Goods.builder()
                .goodsId(goods.getGoodsId())
                .name(goods.getGoodsName())
                .pic(goodsPhotoService.getPath(goods.getGoodsId()))
                .build());
        if (OneListUtil.isEmpty(mainGoodsList)) {
            //每日精选
            List<Goods> daySelect = goodsApiCrmJxsMapper.selectDaySelect(request.getCompanyId());
            List<SupplierWebsiteResponse.Goods> dayGoodsList = ConvertUtils.list(daySelect, goods -> SupplierWebsiteResponse.Goods.builder()
                    .goodsId(goods.getGoodsId())
                    .name(goods.getGoodsName())
                    .pic(goodsPhotoService.getPath(goods.getGoodsId()))
                    .build());
            if (OneListUtil.isNotEmpty(dayGoodsList)) {
                mainGoodsList = dayGoodsList.size() > 3 ? dayGoodsList.subList(0, 3) : dayGoodsList;
            }
        }

        CompanyShowroom companyShowroom = companyShowroomService.getByCompanyId(request.getCompanyId());

        SupplierWebsiteResponse websiteResponse = SupplierWebsiteResponse.builder()
                .photos(model.getPhotos())
                .companyIntroduce(model.getCompanyIntroduce())
                .goodsIntroduce(model.getGoodsIntroduce())
                .address(model.getAddress())
                .latitude(model.getLatitude())
                .longitude(model.getLongitude())
                .phone(model.getPhone())
                .showRoomState(CompanyBaseService.SHOWROOMSTATE_OPEN.equals(company.getShowroomstate()))
                .showRoomUrl(companyShowroom == null ? "" : companyShowroom.getVrUrl())//company 表展厅地址showRoomUrl 替换成 company_showroom 表vr_url
                .recruitModelList(recruitModels)
                .companyVideoModelList(videoModels)
                .mainGoodsList(mainGoodsList)
                .build();


        RequestContext.User user = RequestContextHolder.getRequestContext().getUser();
        final boolean isLogin = Objects.nonNull(user);
        final Integer optCompanyId = isLogin ? user.getCompanyId() : null;
        if (isLogin && !request.getCompanyId().equals(optCompanyId)) {//添加查看记录
            SeeRecordWebsiteRequest recordWebsiteRequest = SeeRecordWebsiteRequest.builder()
                    .userId(user.getUserId())
                    .cardId(user.getCardId())
                    .companyId(request.getCompanyId())
                    .itemId(model.getWebsiteId())
                    .build();
            seeRecordFeign.website(recordWebsiteRequest);
        }

        return ResultModel.success(websiteResponse);
    }
}
